package com.df.ez_game.server;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wqy
 * @since 2022-08-19
 *
 * 用于监测 channel 的心跳的 handler
 *
 */
@Slf4j
public class NettyHeartBeatHandler extends ChannelInboundHandlerAdapter {
    private HeartBeatCallBack cb;

    public NettyHeartBeatHandler(HeartBeatCallBack cb){
        this.cb = cb;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 判断 Event 是否是 IdleStatement (用于触发用户事件, 包含 读空闲|写空闲|读写空闲)
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                if(cb!=null){
                    cb.onReadIdle(ctx,event);
                }
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                if(cb!=null){
                    cb.onWriterIdle(ctx,event);
                }
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                if(cb!=null){
                    cb.onAllIdle(ctx,event);
                }
            }
        }
    }
}
